import { message } from "ant-design-vue";
import type {
  AxiosError,
  AxiosRequestConfig,
  AxiosResponse,
  InternalAxiosRequestConfig,
} from "axios";
import axios from "axios";

import appConfig from "@/config";
import useUserStore from "@/store/userStore";
import { convertError } from "./error/04error.converter";



// const TOKEN_INVALID = "Token认证失败，请重新登录";
// const NETWORK_ERROR = "网络请求异常，请稍后重试";
const service = axios.create({
  baseURL: appConfig.baseApi,
  timeout: 80000,
});
console.log("appConfig",appConfig.baseApi)

// 请求拦截
service.interceptors.request.use((config: InternalAxiosRequestConfig) => {
  console.log("请求参数",config)

  const headers = config.headers;

  const {token }  = useUserStore();
  if (!headers["Authorization"] && token) {
    headers.Authorization = `Bearer ${token}`;
  
  }
  return config;
});
// 响应拦截
service.interceptors.response.use(

  (res: AxiosResponse) => {
    console.log("返回结果",res);
    const { status,message: msg,content} = res.data;
    if (status ==200) {
    
      console.log("request", content);
      message.success(msg)
      return content;
    } else  {
      const { message:msg,errors} = res.data;
      message.error(msg);
      message.error(errors.defaultMessage);
      return Promise.reject(msg);
    }
  },
  (error: AxiosError)=>{
  
    convertError(error);
    return Promise.reject(error);

  }
  // (error: AxiosError) => {
  //   if (error.response) {
  //     let msg = "";
  //     const status = error.response.status;
  //     switch (status) {
  //       case 401:
  //         msg = "token过期";
  //         break;
  //       case 403:
  //         msg = "无权访问，请求方式错误";
  //         break;
  //       case 404:
  //         msg = "请求地址错误";
  //         break;
  //       case 500:
  //         msg = "服务器错误"; // 修正了这里
  //         break;
  //       default:
  //         msg = "无网络或未知错误"; // 提供更通用的错误信息
  //     }
  //     message.error(msg);
  //     return Promise.reject(error);
  //   } else {
  //     // 处理无响应情况，如网络断开等
  //     message.error("无网络连接");
  //     return Promise.reject(error);
  //   }
  // }
);

interface RequestOptions extends AxiosRequestConfig {
  mock?: boolean;
}
/**
 * @description 请求核心函数
 * @param {*} options 请求配置
 *
 */
function request<T>(options: RequestOptions): Promise<T> {
  options.method = options.method?.toLowerCase() || "get";
  if (options.method === "get") {
    options.params = options.data;
  }
  const isMock = options.mock ?? appConfig.mock;

  if (appConfig.env == "prod") {
    service.defaults.baseURL = appConfig.baseApi;
  } else {
    service.defaults.baseURL = isMock ? appConfig.mockApi : appConfig.baseApi;
  }
  return service(options) as Promise<T>;
}

// ["get", "post", "put", "delete", "patch"].forEach((Item) => {
//   request[Item] = (url, data, options) => {
//     return request({
//       url,
//       data,
//       method: Item,
//       ...options,
//     });
//   };
// });

// 为request函数添加快捷方法
["get", "post", "put", "delete", "patch"].forEach((method) => {
  (request as any)[method] = (
    url: string,
    data?: any,
    options?: RequestOptions
  ) => {
    return request({ url, data, method, ...options });
  };
});

export default request;
